#ifndef _SEMAPHOREMGR_H_
#define _SEMAPHOREMGR_H_

#include "../Common/AllTool.h"

class SemaphoreMgr
{
private:
	std::queue<HANDLE>	qHandle;
	CRITICAL_SECTION	csMutex;
	void Lock()
	{
		EnterCriticalSection(&csMutex);
	}
	void Unlock()
	{
		LeaveCriticalSection(&csMutex);
	}
public:
	SemaphoreMgr()
	{
		InitializeCriticalSection(&csMutex);
	}
	~SemaphoreMgr()
	{
		HANDLE h;
		while( !qHandle.empty() )
		{
			h = qHandle.front();
			qHandle.pop();
			CloseHandle(h);
		}
		DeleteCriticalSection(&csMutex);
	}
	
	int GetSemaphore(HANDLE &hSemaphore)
	{
		Lock();
		if( qHandle.empty() )
		{
			hSemaphore = CreateSemaphore(NULL,0,5,NULL);
		}
		else
		{
			hSemaphore = qHandle.front();
			qHandle.pop();
		}
		Unlock();
		if( hSemaphore == NULL )
			return 1;
		return 0;
	}
	int ReturnSemaphore(HANDLE hSemaphore)
	{
		Lock();
		qHandle.push(hSemaphore);
		Unlock();
		return 0;
	}

};

#endif